import multiprocessing

from filelock import FileLock
import json
import os
import sys
from contextlib import asynccontextmanager
import uvicorn
from fastapi import FastAPI, Request
from starlette.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi.openapi.docs import get_swagger_ui_html

from models.db import engine, Base
from router import api_router_v1, api_router_v2
from views import scheduler_start
from views.utils.log import Loggers
from pydantic import BaseModel

root_path = os.getcwd()
sys.path.append(root_path)

Base.metadata.create_all(bind=engine)

lock = FileLock("scheduler.lock")

@asynccontextmanager
async def lifespan(app: FastAPI):
    """使用文件锁，避免任务调度重复启动"""
    # 打开文件
    with lock:
        scheduler_start()
    yield

    # 解锁


app = FastAPI(docs_url=None, lifespan=lifespan)
# app = FastAPI(docs_url=None)
app.include_router(api_router_v1, prefix="/v1")
app.include_router(api_router_v2, prefix="/v2")

if not os.path.isdir('depository'):
    os.mkdir('depository')

# app.mount("/static", StaticFiles(directory="depository"), name="depository")
app.mount("/static", StaticFiles(directory="static"), name="static")

app.add_middleware(
    CORSMiddleware,
    # 允许跨域的源列表，例如 ["http://www.example.org"] 等等，["*"] 表示允许任何源
    allow_origins=["*"],
    # 跨域请求是否支持 cookie，默认是 False，如果为 True，allow_origins 必须为具体的源，不可以是 ["*"]
    allow_credentials=False,
    # 允许跨域请求的 HTTP 方法列表，默认是 ["GET"]
    allow_methods=["*"],
    # 允许跨域请求的 HTTP 请求头列表，默认是 []，可以使用 ["*"] 表示允许所有的请求头
    # 当然 Accept、Accept-Language、Content-Language 以及 Content-Type 总之被允许的
    allow_headers=["*"],
)


# 自定义 Swagger UI 使用本地静态资源
@app.get("/docs", include_in_schema=False)
async def swagger_ui_html():
    return get_swagger_ui_html(
        openapi_url=app.openapi_url,
        title="Swagger UI",
        swagger_js_url="/static/swagger-ui-bundle.js",
        swagger_css_url="/static/swagger-ui.css",
    )


# @app.on_event('shutdown')
# async def shutdown_event():
#     await app.state.redis.close()

class TestSchema(BaseModel):
    operationName: str
    variables: dict
    query: str


@app.post('/graphql')
def graphql(request: Request, form: TestSchema):
    print(json.dumps(dict(request.headers)))
    return 'sdf'


if __name__ == '__main__':
    multiprocessing.freeze_support()

    config = uvicorn.Config("main:app", host='0.0.0.0', port=7006, reload=False, )
    server = uvicorn.Server(config)

    # 将uvicorn输出的全部让loguru管理
    Loggers.init_config()
    server.run()
